package lookas;

import java.io.IOException;
import java.io.StringReader;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XmlParser{

    public static final String OPIS   = "opis";
    public static final String PLAKAT = "plakat";
    public static final String OCENA  = "ocena";
    public static final String LINK   = "link";
    public static final String ROK    = "rok";
    public static final String TYTUL  = "tytul";

    public Map<String, String> parse(String text)
        throws ParserConfigurationException, SAXException, IOException,
        TransformerException{

        DocumentBuilder db = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder();
        Document xmldoc = db.parse(new InputSource(new StringReader(text)));
        Map<String, String> ret = new LinkedHashMap<String, String>();

        Node h = xmldoc.getElementsByTagName("h1").item(0);
        ret.put(TYTUL, h.getFirstChild().getNodeValue());
        ret.put(ROK, h.getLastChild().getChildNodes().item(1).getFirstChild()
            .getNodeValue());

        Node r = xmldoc.getElementsByTagName("root").item(0);
        NamedNodeMap atrs = r.getAttributes();
        ret.put(LINK, atrs.getNamedItem("src").getNodeValue());
        Node b = xmldoc.getElementsByTagName("b").item(0);
        String ocena = b.getFirstChild().getNodeValue().split("/")[0];
		ret.put(OCENA, ocena);
        Node img = xmldoc.getElementsByTagName("img").item(0);
        NamedNodeMap attrs = img.getAttributes();
        String s = attrs.getNamedItem("src").getNodeValue();
        if(s.equals("http://ia.imdb.com/media/imdb/01/I/37/58/83/10.gif"))
            s = null;
        ret.put(PLAKAT, s);

        NodeList p = xmldoc.getElementsByTagName("p");
        String opis = "";
        for(int i = 0; i < p.getLength(); i++){
            opis += "<p>";
            opis += p.item(i).getFirstChild().getNodeValue();
            opis += "</p>";
        }

        ret.put(OPIS, opis);
        return ret;
    }
}
